package com.laoniu.service.base;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.laoniu.dto.request.BaseGoodsRequestDto;
import com.laoniu.entity.BaseGoods;
import com.laoniu.entity.SecurityUser;
import com.laoniu.mapper.BaseGoodsMapper;
import com.laoniu.utils.SpringSecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 商品信息表 服务实现类
 * </p>
 *
 * @author lxl
 * @since 2023-12-17
 */
@Service
public class BaseGoodsService extends ServiceImpl<BaseGoodsMapper, BaseGoods>{

    @Resource
    private BaseGoodsMapper baseGoodsMapper;

    public Page<BaseGoods> listPage(BaseGoodsRequestDto requestDto) {
        SecurityUser user = SpringSecurityUtils.getUser();
        Page<BaseGoods> page = new Page<>(requestDto.getPageNo(), requestDto.getPageSize());
        LambdaQueryWrapper<BaseGoods> wrapper = Wrappers.lambdaQuery(BaseGoods.class);
        wrapper.like(StringUtils.isNotBlank(requestDto.getName()), BaseGoods::getName, requestDto.getName());
        wrapper.eq(Objects.nonNull(requestDto.getSupplier()), BaseGoods::getBaseSupplier, requestDto.getSupplier());
        wrapper.eq(StringUtils.isNotBlank(requestDto.getProductBatchNum()), BaseGoods::getProductBatchNum, requestDto.getProductBatchNum());
        wrapper.eq(StringUtils.isNotBlank(requestDto.getApprovalNumber()), BaseGoods::getApprovalNumber, requestDto.getApprovalNumber());
        wrapper.eq(!user.isAdmin(), BaseGoods::getOpId, user.getId());
        wrapper.orderByDesc(BaseGoods::getId);
        return baseGoodsMapper.selectPage(page, wrapper);
    }

    public List<BaseGoods> goodsBySupplier(Long supplierId) {
        LambdaQueryWrapper<BaseGoods> wrapper = Wrappers.lambdaQuery(BaseGoods.class);
        wrapper.eq(Objects.nonNull(supplierId),BaseGoods::getBaseSupplier, supplierId);
        wrapper.orderByDesc(BaseGoods::getId);
        return baseGoodsMapper.selectList(wrapper);
    }

    public void addNum(Long goodsId, Integer num) {
        BaseGoods baseGoods = baseGoodsMapper.selectById(goodsId);
        if (Objects.isNull(baseGoods)){
            return;
        }
        baseGoods.setNum(baseGoods.getNum() + num);
        baseGoodsMapper.updateById(baseGoods);
    }
}
